package br.usp.pcs.basys2.engine;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import br.usp.pcs.basys2.Activity;
import br.usp.pcs.basys2.ActivityDuty;
import br.usp.pcs.basys2.DutyGenerator;
import br.usp.pcs.basys2.info.ProcessInfo;

public final class RandomGenerator implements DutyGenerator {
	private Random random = new Random();
	

	public SortedSet<ActivityDuty> produceDuties(ProcessInfo processInfo) {
		List<Activity> activities = processInfo.getAllActivities();
		if (activities.size() >= processInfo.getCpuTotalTime()) {
			throw new IllegalArgumentException(
					"Nao sera possivel gerar atividades em instantes diferentes.");
		}
		SortedSet<ActivityDuty> result = new TreeSet<ActivityDuty>();
		Set<Integer> chosenStartTimes = new HashSet<Integer>();
		Collections.shuffle(activities);
		for (Activity activity : activities) {
			ActivityDuty duty = new ActivityDuty();
			int time;
			duty.setActivity(activity);
			do {
				time = (random.nextInt(processInfo.getCpuTotalTime() - 1)) + 1;
				// 0 <time< cpuTotalTime
			} while (!chosenStartTimes.add(time));
			// Garante que os tempos escolhidos serao diferentes
			duty.setStartTime(time);
			result.add(duty);
		}
		return result;
	}
}